package oop.core.med;
import oop.core.Scheduler;
import oop.core.entity.*;
import oop.core.map.*;
import oop.core.visitors.InteractiveItemVisitable;
import oop.core.visitors.InteractiveItemVisitor;
import oop.core.item.*;
import java.util.*;

public class AvatarMovementMediator extends EntityMovementMediator implements Pausable
{
	private Avatar avatar;
	private ItemPickupMediator itemPickupMediator;
	private InteractionItemMediator interactionItemMediator;
	private InteractionMediator interactionMediator;
	private Scheduler scheduler;
	private boolean paused;
	
	public AvatarMovementMediator(Avatar avatar, ItemPickupMediator itemPickupMediator, InteractionItemMediator interactionItemMediator, InteractionMediator interactionMediator, GameMap gameMap, MovementLogic movementLogic, Scheduler scheduler)
	{
		super(gameMap, movementLogic);
		this.avatar= avatar;
		this.itemPickupMediator = itemPickupMediator;
		this.interactionItemMediator = interactionItemMediator;
		this.interactionMediator = interactionMediator;
		this.scheduler = scheduler;
		paused = false;
		canMove = true;
	}
	public void moveEntity(int direction)
	{
		if( paused || !canMove )
		{
			return;
		}
		
		Location avatarLocation;
		Location newLocation;
		List<MovementType> movementType;

		avatarLocation = avatar.getLoc();
		movementType = avatar.getMovementTypes();

		avatar.setDirection(direction);

		// return a location to move to
		// otherwise, return null
		newLocation = movementLogic.move(movementType, avatarLocation, direction);
		Location desiredLocation = movementLogic.calcDesiredLocation(avatarLocation, direction);
		if(newLocation != null){
			canMove = false;
			scheduler.register( this, 10000 / avatar.getMovement() );
			
			avatar.setLoc(newLocation);
			TakeableItem item = gameMap.getTakeableItemAt(newLocation);
			if(item != null){
				itemPickupMediator.pickup(item);
			}
		}
		else{
    //entity or interactiveitem
			InteractiveItemVisitable itemVisitable = gameMap.getInteractiveItemVisitableAt(desiredLocation);
			if(itemVisitable != null){
				System.out.println("Hey, I interact with an item!");
				interactionItemMediator.interact(itemVisitable, desiredLocation);
			}

			if(movementLogic.containsEntity(desiredLocation)){
				Entity entity = gameMap.getEntity(desiredLocation);
				boolean hostile = ((NPC)entity).isHostile();
				if(hostile)
				{
					avatar.attackEntity(entity);
				}
				else
				{
					interactionMediator.interact((NPC)entity);
				}
			}
			
		}
	}

	public void pause() {
		paused = true;
	}
	
	public void toggle() {
		paused = !paused;
	}
	@Override
	public void unpause() {
		paused = false;	
	}
	
	public void toggleHide()
	{
		avatar.toggleHide();
	}

}
